<?php
// +----------------------------------------------------------------------
// | 会员卡数据处理
// +----------------------------------------------------------------------
// | Author: TongBC <501468940@qq.com>
// +----------------------------------------------------------------------
// | Date  : 2015/03/06
// +----------------------------------------------------------------------
include_once '/var/www/html/new/com.inc.php';
include_once '/var/www/html/new/d/common/func.inc.php';
include_once '/var/www/html/new/d/class/MemberAccount.class.php';
include_once '/var/www/html/new/d/class/abc/Tools.class.php';
include_once '/var/www/html/new/d/class/abc/Validate.class.php';

$ac=$GLOBALS['_ac'];
$pw=$GLOBALS['_pw'];
$s = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));

if(!isset($_SESSION['sid'])) exit('{"status":"fail","msg":"登陆超时","code":0}');


switch(trim($_REQUEST['action'])) {
	
	
	
	// 资质认证
	case 'accredits':
		$recv = _addslashes($_REQUEST);// 接收数据
		$did = $_REQUEST['did'] + 0;
		if($did==0) exit('{"status":"fail","msg":"参数错误"}');
		// 个人
		if($recv['com_type']=='个人'){
			if($recv['id_card'] && !abc777\Validate::isIDCard($recv['id_card'])) exit('{"status":"fail","msg":"身份证格式不正确"}');
			if($recv['id_card_hand']=='') exit('{"status":"fail","msg":"请上传手持身份证正面"}');
			if($recv['id_card_B']=='')    exit('{"status":"fail","msg":"请上传手持身份证背面"}');
			
			if($recv['id_card']){
				$sql = "select id from pft_member_extinfo where id_card_no='{$recv['id_card']}' limit 1";
				$GLOBALS['le']->query($sql);
				if($GLOBALS['le']->fetch_assoc()) {
					echo '{"status":"fail","msg":"身份证已存在"}';
					break;
				}
			}

			
			// $idCard    = $recv['id_card'];
			$save['id_card_no']    = $recv['id_card'];
			$save['id_card_B']     = $recv['id_card_B'];
			$save['other_les']     = $recv['other_les'];
			$save['id_card_hand']  = $recv['id_card_hand'];
			$save['certi_status']  = ($_SESSION['sid']==$did) ? 1:2;
			if($_SESSION['sid']==$did){
				$save['pass_time'] = date('Y-m-d H:i:s');
			}
			$sql = _updateSqlBuild($save, 'pft_member_extinfo')." where fid=$did and certi_status<>2 limit 1";
			$response = $GLOBALS['le']->query($sql) ? '{"status":"success","msg":"保存成功"}':'{"status":"fail","msg":"保存失败，请重新保存"}';
			echo $response;
            break;
		}
		
		// 公司
		$save['bsn_les']  = $recv['bsn_les'];
		$save['opt_les']  = $recv['opt_les'];
		$save['tax_les']  = $recv['tax_les'];
		$save['org_les']  = $recv['org_les'];
		$save['auth_les'] = $recv['auth_les'];
		if($recv['bsn_les']=='') exit('{"status":"fail","msg":"请上传资质认证"}');
		if($recv['org_les']=='') exit('{"status":"fail","msg":"请上传组织机构代码证"}');
		if($recv['tax_les']=='') exit('{"status":"fail","msg":"请上传税务登记证"}');
		$save['certi_status']  = ($_SESSION['sid']==$did) ? 1:2;
		if($_SESSION['sid']==$did){
			$save['pass_time'] = date('Y-m-d H:i:s');
		}
		$sql = _updateSqlBuild($save, 'pft_member_extinfo')." where fid=$did and certi_status<>2 limit 1";
		$response = $GLOBALS['le']->query($sql) ? '{"status":"success","msg":"保存成功"}':'{"status":"fail","msg":"保存失败，请重新保存"}';
        echo $response;
		break;
		
	// 会员卡配置受理
	case 'accept':
		$recv = _addslashes($_REQUEST);// 接收数据
		// write_logs(json_encode($recv));
		// exit;
		$did = $recv['did'] + 0;
		if($did==0 ||$recv['phy_no']=='') exit('{"status":"fail","msg":"参数错误"}');
		
		// 大小端数据转化
		$phy_no_arr = str_split($recv['phy_no'], 2);
		krsort($phy_no_arr);
		$recv['phy_no'] = hexdec(implode('',$phy_no_arr));
		
		$fill_id = 0;// 补卡标志
		
		if($recv['cid']>0){// 
			$sql = "select status,physics_no from pft_member_card where id={$recv['cid']} limit 1";
			$GLOBALS['le']->query($sql);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f('status')==1){
				$fill_id = $recv['cid'];
				$recv['cid']=0;
				$res_phy_no = $GLOBALS['le']->f('physics_no');
			}
		}
		
		// exit;
		if($recv['cid']==0){// 开卡
			if($recv['password']==''){
                echo '{"status":"fail","msg":"请输入消费密码"}';
                break;
            }
			
			if($recv['password']!=$recv['chPassword']) {
                echo '{"status":"fail","msg":"消费密码不一致"}';
                break;
            }
			$sql = "select id from pft_member_card where card_no='{$recv['card_no']}' limit 1";
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()) {
                echo '{"status":"fail","msg":"IC卡编号重复"}';
                break;
            }
			
			$sql = "select id from pft_member_card where physics_no='{$recv['phy_no']}' limit 1";
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()) {
                echo '{"status":"fail","msg":"IC卡物理卡号重复"}';
                break;
            }
			
			$sql = "select id from pft_member_card where memberID=$did and status<4 and status<>1 order by id desc limit 1";
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
                echo '{"status":"fail","msg":"该分销商已办理会员卡"}';
                break;
            }
			
			$save = array();
			$save['memberID']    = $recv['did'];// 办卡用户ID
			$save['apply_did']   = $_SESSION['sid'];// 开卡供应商ID
			$save['card_no']     = $recv['card_no'];// IC卡编号
			$save['physics_no']  = $recv['phy_no'];// IC卡物理卡号
			$save['notice_type'] = $recv['notice_type'];// 消费通知类型
			$save['card_time']   = date('Y-m-d H:i:s');// 开卡时间
			$save['password']    = md5(md5($recv['password']));// 消费密码
			$sql = _insertSqlBuild($save,'pft_member_card');

			// echo $sql;
			// exit;
			$recv['cid'] = $GLOBALS['le']->query($sql) ? mysql_insert_id():0;
			if($recv['cid']==0){
                echo '{"status":"fail","msg":"开卡失败，请重试"}';
                break;
            }
			if($fill_id>0){// 补卡 数据转移
				
				$upd = "update pft_member_card set status=4 where id=$fill_id limit 1";
				$GLOBALS['le']->query($upd);
				write_logs($upd);
				$upd = "update pft_card_consume_conf set card_id={$recv['cid']},card_phyNo={$recv['phy_no']} where card_id=$fill_id and memberID=$did and card_phyNo='$res_phy_no'";
				$GLOBALS['le']->query($upd);
			}
				
		}

		// 更改消费密码
		if($recv['password']!=''){
			if($recv['password']!=$recv['chPassword']){
                echo '{"status":"fail","msg":"消费密码不一致"}';
                break;
            }
			$pass = md5(md5($recv['password']));
			$sql = "update pft_member_card set password='$pass' where id={$recv['cid']} limit 1";
			if(!$GLOBALS['le']->query($sql)){
                echo '{"status":"fail","msg":"消费密码修改失败"}';
                break;
            }
		}
		
		// 供应商对持会员卡分销商消费配置
		$save_ext = array();
		$save_ext['daily_buy_limit'] = $recv['daily_limit'] + 0;
		$save_ext['buy_interval'] = $recv['interval'] + 0;
		$save_ext['buy_num_limit'] = $recv['num_limit'] + 0;
		$save_ext['verify_time'] = date('Y-m-d H:i:s');
		if($recv['config_id']){// 编辑
			$upd = _updateSqlBuild($save_ext, 'pft_card_consume_conf');
			$upd = $upd." where id={$recv['config_id']} and card_id={$recv['cid']} limit 1";
			echo $GLOBALS['le']->query($upd) ? '{"status":"success","msg":"保存成功"}':'{"status":"fail","msg":"保存失败，请重新保存"}';
			break;
		}
		$save_ext['config_time'] = date('Y-m-d H:i:s');
		$save_ext['card_id']     = $recv['cid'];
		$save_ext['apply_did']   = $_SESSION['sid'];// 供应商ID
		$save_ext['memberID']    = $recv['did'];// 分销商ID
		$save_ext['card_phyNo']  = $recv['phy_no'];
		
		// 再次判断唯一性
		$sql = "select id from pft_card_consume_conf where apply_did={$_SESSION['sid']} and memberID=$did limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
            echo '{"status":"fail","msg":"配置不唯一"}';
            break;
        }
		$sql = _insertSqlBuild($save_ext,'pft_card_consume_conf');
		
		echo $GLOBALS['le']->query($sql) ? '{"status":"success","msg":"保存成功"}':'{"status":"fail","msg":"保存失败，请重新保存"}';
		break;


		
	// 获取6位验证码
	case 'code':
		if(!isset($_REQUEST['mobile'])) exit('{"status":"fail","msg":"请输入手机号"}');
		if(strlen($_REQUEST['mobile'])!=11 && !is_tel($_REQUEST['mobile'])) exit('{"status":"fail","msg":"您输入的手机格式有误"}');
		$clsResult = abc777\Tools::MobileCode6($s, $_REQUEST['mobile'], 10);
		if($clsResult['code']==100){
            echo '{"status":"success","msg":"发送成功"}';
            break;
        }
		echo '{"status":"fail","msg":"'.$clsResult['msg'].'"}';
		break;



	// 根据手机号查询用户
	case 'valiUser':
		$mobile = $_REQUEST['mobile'];
		$sql = "select id from pft_member where account='$mobile' or mobile='$mobile' limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()){
            echo '{"status":"fail","msg":"未匹配到数据"}';
            break;
        }
		exit('{"status":"success","exists_f":1,"msg":"存在"}');
		break;
		
	// 检查手机验证码
	case 'valiCode':
		$valicode = $_REQUEST['vcode'];
		$clsResult = abc777\Tools::ValiMobileCode($valicode);
		if($clsResult['code']==100) exit('{"status":"success","msg":"发送成功"}');
		if($clsResult['code']==101) exit('{"status":"fail","msg":"验证码已失效，请重新获取"}');
		if($clsResult['code']==102) exit('{"status":"fail","msg":"验证码不正确"}');
		break;
		
		
	// 获取已配置会员列表
	case 'list':
		$sid = $_SESSION['sid'];
		$pageSize = isset($_REQUEST['pageSize']) ? $_REQUEST['pageSize']+0:15;
		// $pageSize = 15;
		$currentPage = isset($_REQUEST['currentPage']) ? $_REQUEST['currentPage']+0:1;
		$pageStart = ($currentPage - 1) * $pageSize;
		$response = array(// 异步返回数据
			'list'        => array(),
			'page'        => $currentPage,
			'pageSize'    => $pageSize,
			'totalpage'   => 0
		);
		// 搜索条件
		$where = "where c.apply_did=$sid";
		if(isset($_REQUEST['status']) && $_REQUEST['status']!=''){
			 $where.=' and mc.status='.($_REQUEST['status']+0);
		}else{
			 $where.=' and mc.status<4';
		}
		if(isset($_REQUEST['keyword']) && $_REQUEST['keyword']!=''){
			// $keyword = $_REQUEST['keyword'] + 0;
			$keyword = $_REQUEST['keyword'];
			if(abc777\Validate::isMobile($_REQUEST['keyword'])){// 手机号
				$where.=" and m.mobile='$keyword'";
			}elseif(is_numeric($_REQUEST['keyword'])){
				$where.=" and mc.card_no='$keyword'";
			}else{
				$where.=" and m.dname='$keyword' or m.cname='$keyword'";
			}
		}

		
		
		// 获取已配置的分销商
		$sql = "select m.dname,m.cname,m.id as did,m.mobile,c.daily_buy_limit,c.buy_interval,c.buy_num_limit,mc.status,mc.card_no,mc.id as cid"; 
		$sql.= ",c.id as config_id ";
		$sql.= "from pft_card_consume_conf c left join pft_member m on m.id=c.memberID left join pft_member_card mc on c.card_id=mc.id ";
		$sql.= "$where limit $pageStart,$pageSize";
		// echo $sql;
		$GLOBALS['le']->query($sql);
		while($row=$GLOBALS['le']->fetch_assoc()){
			$response['list'][] = $row;
		}
		
		// 获取总数
		$sql = "select count(c.id) as count "; 
		$sql.= "from pft_card_consume_conf c left join pft_member m on m.id=c.memberID left join pft_member_card mc on c.card_id=mc.id ";
		$sql.= "$where";
		$GLOBALS['le']->query($sql);
		$GLOBALS['le']->fetch_assoc();
		$response['totalpage'] = ceil($GLOBALS['le']->f('count') / $pageSize);
		// write_logs(json_encode($response));
		exit(json_encode($response));
		break;
	// 编辑会员卡购买限制
	case 'edit_conf':
		$recv = _addslashes($_REQUEST);// 接收数据
		$did = $recv['did'] + 0;// 分销商
		
		if(!isset($recv['config_id']) || !isset($recv['cid']) ||  $did==0) exit('{"status":"fail","msg":"参数错误"}');

		// 供应商对持会员卡分销商消费配置
		$save = array();
		
		if(isset($recv['daily_limit'])) $save['daily_buy_limit'] = $recv['daily_limit'] + 0;
		if(isset($recv['interval']))    $save['buy_interval']    = $recv['interval'] + 0;
		if(isset($recv['num_limit']))   $save['buy_num_limit']   = $recv['num_limit'] + 0;
		
		$save['verify_time']     = date('Y-m-d');
		$upd = _updateSqlBuild($save, 'pft_card_consume_conf')." where id={$recv['config_id']} and card_id={$recv['cid']} limit 1";;
		echo $GLOBALS['le']->query($upd) ? '{"status":"success","msg":"保存成功"}':'{"status":"fail","msg":"保存失败，请重新保存"}';
		break;
	// 挂失
	case 'loss':
		$recv = _addslashes($_REQUEST);// 接收数据
		
		if(!isset($recv['cid']) || !isset($recv['did'])) exit('{"status":"fail","msg":"参数错误"}');
		$did = $recv['did'] + 0;// 分销商
		$cid = $recv['cid'] + 0;// 分销商
		
		// 检查是否挂失过
		$sql = "select status from pft_member_card where id=$cid and memberID=$did limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"会员卡未开通"}');
		if($GLOBALS['le']->f('status')==1) exit('{"status":"fail","msg":"该会员卡已挂失"}');
		
		$sql = "update pft_member_card set status=1 where id=$cid and memberID=$did limit 1";
		echo $GLOBALS['le']->query($sql) ? '{"status":"success","msg":"挂失成功"}':'{"status":"fail","msg":"挂失失败"}';
		break;
	
	// 禁用会员卡
	case 'chstatus':
		$recv = _addslashes($_REQUEST);// 接收数据
		
		if(!isset($recv['cid']) || !isset($recv['did'])) exit('{"status":"fail","msg":"参数错误"}');
		$did = $recv['did'] + 0;// 分销商
		$cid = $recv['cid'] + 0;// 记录ID
		$pass = md5(md5($recv['password']));
		$status = $recv['status'] + 0;// 分销商

		// 检查会员卡状态
		$sql = "select status,password from pft_member_card where id=$cid and memberID=$did limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"会员卡未开通"}');
		
		if($status!=2){
			if($pass!=$GLOBALS['le']->f('password')) exit('{"status":"fail","msg":"消费密码错误"}');
		}
		
		
		$dstatus = $GLOBALS['le']->f('status');
		

		// 启用与禁用会员卡
		if(($status==0 || $status==2) && ($dstatus==4)) exit('{"status":"fail","msg":"该会员卡已废弃"}');

		// 挂失请求
		if($status==1 && $dstatus==1)  exit('{"status":"fail","msg":"该会员卡已挂失"}');
		
		
		$sql = "update pft_member_card set status=$status where id=$cid and memberID=$did limit 1";
		echo $GLOBALS['le']->query($sql) ? '{"status":"success","msg":"操作成功"}':'{"status":"fail","msg":"操作失败"}';
		break;

	// 修改用户资料
	case 'modify_user':
	
		$recv = _addslashes($_REQUEST);// 接收数据
		$did = $recv['did'] + 0;
		
		if(!abc777\Validate::isIDCard($recv['idcard'])) exit('{"status":"fail","msg":"身份证格式不正确"}');
		$sql = "select fid from pft_member_extinfo where id_card_no='{$recv['idcard']}' limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc() && $GLOBALS['le']->f('fid')!=$did) exit('{"status":"fail","msg":"身份证已存在"}');
		
		if($did==0){// 新增
			$dataMain    = array();
			$dataExtInfo = array();
			$todo = $_REQUEST['actionType'];
			//TODO:注册验证码校验
			if(trim($recv['vcode'])!=$_SESSION['vcode'] ) exit('{"status":"fail","msg":"验证码错误"}');
			
			// if($recv['dname']=='') exit('{"status":"fail","msg":"请输入账号名称"}');
			if($recv['cname']=='') exit('{"status":"fail","msg":"请输入联系人"}');
			
			$dataMain['cname'] = $recv['cname'];// 联系人
			$dataMain['dname'] = $recv['cname'];// 账户名称
			
			$dataMain['dtype'] = 1; 
			$dataMain['status'] = 0;
			$dataExtInfo['com_name'] = $dataMain['cname'];// 公司名称默认账号名称
			$dataExtInfo['com_type'] = '个人';// 公司类型
			$dataMain['mobile'] = $recv['mobile'];
			if(!ismobile($dataMain['mobile'])) exit('{"status":"fail","msg":"手机号格式不正确"}');
			$dataExtInfo['sex'] = trim($recv['sex']);//性别

			$pwd_res=chkPassword($recv['password'], $recv['confirmPwd']);
			if($pwd_res!=1) exit('{"status":"fail","msg":"$pwd_res"}');
			if($recv['password']!=$recv['confirmPwd']) exit('{"status":"fail","msg":"密码不一致"}');
			$dataMain['password'] = md5(md5($_POST['password']));
			$dataExtInfo['id_card_no'] = $recv['idcard'];
			// 邀请人
			$dataMain['inviterID'] = $_SESSION['sid'];
			// print_r($dataMain);
			// print_r($dataExtInfo);
			// exit;
			$mem = new pft\Member\MemberAccount($GLOBALS['le'], $_SESSION['sid']);
			$result = $mem->register($dataMain, $dataExtInfo);
			// write_logs(json_encode($result));
			echo json_encode($result);
			exit;
		}
		
		// 编辑用户资料
		$cname      = $recv['cname'];
		$qq         = $recv['qq'];
		$id_card_no = $recv['idcard'];
		$sql = "update pft_member set qq='$qq',cname='$cname' where id=$did limit 1";
		if($GLOBALS['le']->query($sql)){
			$sex = $recv['sex'];
			$sql = "update pft_member_extinfo set sex='$sex',id_card_no='$id_card_no' where fid=$did limit 1";
			$GLOBALS['le']->query($sql);
			echo '{"status":"success","msg":"更新成功"}';
            break;
		}
        echo '{"status":"fail","msg":"更新用户资料失败"}';
		break;
	// 原始供应商配置渠道购买限制
	case 'restrict':
		$recv = _addslashes($_REQUEST);// 接收数据
		// print_r($recv);
		// exit;
		$save = array();
		$pid = $recv['pid']+0;// 产品ID
		$rid = $recv['rid']+0;// 
		
		if($pid==0) exit('{"status":"fail","msg":"参数错误"}');
		if($rid==0){// 新增
			// 限制重复判断
			$sql = "select id from pft_prod_restrict where pid=$pid limit 1";
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"产品已配置"}');
			$save['daily_buy_limit'] = $recv['daily_limit'] + 0;
			$save['buy_interval']    = $recv['interval'] + 0;
			$save['buy_num_limit']   = $recv['num_limit'] + 0;
			$save['addtime'] = date('Y-m-d H:i:s');
			$save['rst_type'] = 1;
			$save['pid'] = $recv['pid'];
			$sql = _insertSqlBuild($save,'pft_prod_restrict');
			if($GLOBALS['le']->query($sql)){
				echo '{"status":"success","msg":"配置成功"}';
				break;
			}
			echo '{"status":"fail","msg":"配置失败"}';
			break;
		}
		if(isset($recv['daily_limit'])) $save['daily_buy_limit'] = $recv['daily_limit'] + 0;
		if(isset($recv['interval']))    $save['buy_interval']    = $recv['interval'] + 0;
		if(isset($recv['num_limit']))   $save['buy_num_limit']   = $recv['num_limit'] + 0;
		$save['verify_time'] = date('Y-m-d H:i:s');
		$sql = _updateSqlBuild($save, 'pft_prod_restrict')." where id=$rid and pid=$pid limit 1";
		if($GLOBALS['le']->query($sql)){
			echo '{"status":"success","msg":"配置成功"}';
			break;
		}
		echo '{"status":"fail","msg":"配置失败"}';
		break;
    default:break;
	
}

@$GLOBALS['le']->close();
// 数据转义
function _addslashes($data){
	if(is_array($data)){
		foreach($data as $key=>$value){
			$data[$key] = _addslashes($value);
		}
		return $data;
	}
	return addslashes($data);
}

// 生成语句
function _insertSqlBuild($data, $table){
	if(is_null($data)) return '';
	$sql = 'insert into `'.$table.'` set ';
	foreach($data as $field=>$value){
		$sql = $sql.'`'.$field.'`="'.$value.'",';
	}
	return rtrim($sql,',');
}
// 生成编辑语句
function _updateSqlBuild($data, $table){
	if(is_null($data)) return '';
	$sql = 'update `'.$table.'` set ';
	foreach($data as $field=>$value){
		$sql = $sql.'`'.$field.'`="'.$value.'",';
	}
	$sql = rtrim($sql,',');
	return $sql;
}

function write_logs($txt,$file="/var/www/html/new/d/api/logs/data111123456.txt"){
	$fp = fopen($file,"a");
	flock($fp, LOCK_EX);
	fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}
?>